package com.k.kpp.web.easyexcel2.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.k.kpp.web.util.EasyExcelUtils;
import com.k.kpp.web.easyexcel2.domain.ExcelTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@ApiSupport(author = "ljw", order = 31)
@Api(tags = "Excel")
@Validated
@RequestMapping(value = "/excel/template")
public class TemplateController {

    @ApiOperation(value = "模板下载")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "excelType", required = true, dataType = "string", value = "必到点模板填固定值:arrivePoint_excel", example = "arrivePoint_excel")})
    @ApiOperationSupport(order = 60)
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadTemplate(HttpServletResponse res, @RequestParam(value = "excelType") String excelType) throws IOException {
        res.setContentType("application/octet-stream");
        res.addHeader("Pragma", "public");
        res.addHeader("Cache-Control", "max-age=0");
        res.setCharacterEncoding("UTF-8");
        String filename = excelType + "_tpl_" + System.currentTimeMillis();
        res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename + ".xlsx"));
        OutputStream os = res.getOutputStream();
        ExcelTypeEnum.matchOpValue(excelType)
                .ifPresent(a -> EasyExcelUtils.genTemplate(os, a.getModelClass(), null, "SHEET1", null));
    }
}
